<template>
  <div>
    <div style="margin-bottom: 5px;">
      <Button type="success" @click="handleAddRole" :disabled="loadTable">
        <Icon type="android-add"></Icon>
        新增
      </Button>
      <Button type="primary" @click="handleChangePosition" :disabled="loadTable">
        <Icon type="edit"></Icon>
        更改职位
      </Button>
      <Button type="warning" :disabled="loadTable" v-if="curRow && curRow.status=== '1'"
      @click="handleChangeStatusButtonClick('0')">
        <Icon type="close-circled"></Icon>
        禁用
      </Button>
      <Button type="success" :disabled="loadTable" v-else 
      @click="handleChangeStatusButtonClick('1')">
        <Icon type="checkmark"></Icon>
        启用
      </Button>
      <Button type="error" :disabled="loadTable" @click="handleDeleteButtonClick">
        <Icon type="trash-b"></Icon>
         删除
      </Button>
    </div>
    <Table :columns="columns" :data="rowData" :loading="loadTable" 
    border style="margin: 0 auto;text-align:center;"
    highlight-row ref="currentTable"
    :height="tableHeight"
    @on-current-change="handleCurrentRowChange">
    </Table>
  </div>
</template>
<script>
import md5 from 'js-md5';
import querystring from 'querystring';
import { HOST } from '../../libs/config.js';
import { loginInvalid } from "../../libs/loginInvalidNotice.js";
export default {
  props: {

  },
  data() {
    return {
      modalLoading: true,
      tableHeight: 100,
      curRow: null,
      curIndex: -1,
      modalIsOn: false,
      loading: true,
      loadTable: true,
      newPassword: '',
      addForm: {
        'uid': '',
        'name': '',
        'password': '',
        'role_id': []
      },
      updateRole: {
        id: '',
        'role_id': []
      },
      positionList: [
        '',
        '项目负责人',
        '部门主管',
        '中心主管',
        '仓库主管',
        '网站管理员'
      ],
      columns:[
        {
          title: '用户id',
          key: 'id',
          width: 200,
          align: 'center',
        }, 
        {
          title: '工号',
          key: 'uid',
          width: 200,
          align: 'center',
        }, 
        {
          title: '姓名',
          key: 'username',
          width: 200,
          align: 'center',
        },
        {
          title: '职位',
          key: 'position',
          width: 298,
          align: 'center',
          render: (h, params) => {
            let positionList = this.positionList;
            return h('div', params.row.position.split('').map((item) => {
              return h('Tag', {
                props: {
                }
              }, this.positionList[parseInt(item)])
            }))
          }
        },
        {
          title: '最后登入时间',
          key: 'login_time',
          width: 300,
          align: 'center',
        },
        {
          title: '最后登入ip',
          key: 'login_ip',
          width: 300,
          align: 'center',
        },
        {
          title: '用户状态',
          key: 'status',
          width: 200,
          align: 'center',
          render: (h, params) => {
            return h('tag', {
              props: {
                type: 'dot',
                color: params.row.status === '1' ? 'green' : 'red'
              }
            }, params.row.status === '1' ? '正常' : '禁用')
          }
        },
      ],
      rowData: [

      ]
    }
  },
  methods: {
    handleCurrentRowChange(cur) {
      if (cur) {
        this.curRow = cur;
        this.updateRole.id = cur.id;
      }
    },
    refreshData() {
      this.loadTable = true;
      this.$axios.get(HOST + '/user/list', {
        withCredentials: true
      })
      .then((response) => {
        // TODO mock data
        let data = response.data;
        if (data.length > 0) {
          this.rowData = data;
          this.loadTable = false;
        }
      })
      .catch((err) => {
        if (err.data.status === 'invalid Token') {
          loginInvalid(this)();
        }
      })
    },
    handleChangePosition() {
      if (!this.curRow) {
        this.$Notice.warning({
          title: '未选择修改的用户',
          desc: `请点击任意一行选中想要修改的用户`,
            duration: 3
        });
      } else {
        this.$Modal.confirm({
          render: (h) => {
            return h('div',[
              h('div', [
                h('span', {
                  style: {
                    'margin-right': '30px'
                  }
                },'当前职位'),
                h('div', this.curRow.position.split('').map((item) => {
                  return h('Tag', {
                    props: {
                      type: 'dot',
                      color: 'blue'
                    }
                  }, this.positionList[parseInt(item)])
                })),
                
              ]),
              h('div', [
                h('span', {
                  style: {
                    'margin-right': '30px'
                  }
                },'目标职位'),
                h('Select', {
                  style: {
                    width: '250px'
                  },
                props: {
                  value: this.updateRole['role_id'],
                  multiple: true
                },
                  on: {
                    'on-change': (value) => {
                      this.updateRole['role_id'] = value;
                    }
                  }
                }, this.positionList.map((item, index) => {
                  if (item !== '') {
                    return h('Option', {
                      props: {
                        value: String(index)
                      }
                    }, item);
                  }
                  return h();
                }))
              ])

            ])
          },
          loading: true,
          title: '修改职位',
          onOk: () => {
            this.handleUpdateRole();
          },
          onCancel: () => {
            this.$Modal.remove();
          }
        })
      };
    },
    handleUpdateRole() {
      this.$axios.post(HOST + '/user/updateRole',
        querystring.stringify({
          'id': this.updateRole['id'],
          'role_id': this.updateRole['role_id'].sort().join('')
        }), {
          withCredentials: true
        }
      )
      .then((response) => {
        this.$Modal.remove();
        if (response.data.status === 'success') {
          this.$Notice.success({
            title: '更改成功',
            desc: `用户${this.curRow.username}，职位更新成功`,
            duration: 3
          });
          this.refreshData();
        } else {
          this.$Notice.error({
            title: '更改失败',
            desc: `用户${this.curRow.username}，职位更新失败`,
            duration: 3
          });
        }
        this.curRow = null;
        this.$refs.currentTable.clearCurrentRow();
      })
      .catch((err) => {
        if (err.data.status === 'invalid Token') {
          loginInvalid(this)();
        }
      });
    },
    handleAddRole() {
      this.$Modal.confirm({
        render: (h) => {
          return h('div',[
            h('div', {
              style: {
                'margin-bottom': '20px'
              }
            }, [
              h('span', {
                style: {
                  'margin-right': '30px'
                }
              }, '工号'),
              h('Input', {
                props: {
                  value: this.addForm.uid
                },
                attrs: {
                  placeholder: '请输入工号'
                },
                style: {
                  width: '250px'
                },
                on: {
                  'on-blur': (e) => {
                    this.addForm.uid = e.target.value;
                  }
                }
              })
            ]),
            h('div', {
              style: {
                'margin-bottom': '20px'
              }
            }, [
              h('span', {
                style: {
                  'margin-right': '30px'
                }
              }, '姓名'),
              h('Input', {
                props: {
                  value: this.addForm.name
                },
                attrs: {
                  placeholder: '请输入姓名'
                },
                style: {
                  width: '250px'
                },
                on: {
                  'on-blur': (e) => {
                    this.addForm.name = e.target.value;
                  }
                }
              })
            ]),
            h('div', {
              style: {
                'margin-bottom': '20px'
              }
            }, [
              h('span', {
                style: {
                  'margin-right': '30px'
                }
              }, '密码'),
              h('Input', {
                props: {
                  value: this.addForm.password
                },
                attrs: {
                  placeholder: '请输入密码'
                },
                style: {
                  width: '250px'
                },
                on: {
                  'on-blur': (e) => {
                    this.addForm.password = e.target.value;
                  }
                }
              })
            ]),
            h('div',[
              h('span', {
                style: {
                  'margin-right': '30px'
                }
              },'职位'),
              h('Select', {
                style: {
                  width: '250px'
                },
                props: {
                  value: this.addForm['role_id'],
                  multiple: true
                },
                on: {
                  'on-change': (value) => {
                    this.addForm['role_id'] = value;
                  }
                }
              }, this.positionList.map((item, index) => {
                if (item !== '') {
                  return h('Option', {
                    props: {
                      value: String(index)
                    }
                  }, item);
                }
                return h();
              }))
            ])

          ])
        },
        loading: this.modalLoading,
        title: '修改密码',
        onOk: () => {
          this.handleAddRoleButton();
        },
        onCancel: () => {
          this.$Modal.remove();
        }
      })
    },
    handleAddRoleButton() {
      if (this.addForm['uid'] && this.addForm['name'] &&
        this.addForm['password'] && this.addForm['role_id']) {
          this.$axios.post(HOST + '/user/userAdd',
              querystring.stringify({
                'uid': this.addForm['uid'],
                'name': this.addForm['name'],
                'password': md5(this.addForm['password'] + 'gongxun'),
                'role_id': this.addForm['role_id'].sort().join('')
              }), {
                withCredentials: true
              }
            )
            .then((response) => {
              this.$Modal.remove();
              if (response.data.status === 'success') {
                this.$Notice.success({
                  title: '更改成功',
                  desc: `用户${this.addForm.name}添加成功`,
                  duration: 2
                });
                this.refreshData();
              } else {
                this.$Notice.error({
                  title: '更改失败',
                  desc: `用户${this.addForm.name}添加失败`,
                  duration: 2                  
                });
              }
              this.curRow = null;
              this.$refs.currentTable.clearCurrentRow();
            })
            .catch((err) => {
              if (err.data.status === 'invalid Token') {
                loginInvalid(this)();
              }
            })
      } else {
        this.$Modal.remove();
        this.$Notice.warning({
          title: '～～',
          desc: `请填写要添加用户的基本信息`,
          duration: 3
        });
      }
    },
    handleDeleteButtonClick() {
      if (!this.curRow) {
        this.$Notice.warning({
          title: '未选择修改的用户',
          desc: `请点击任意一行选中想要删除的用户`,
          duration: 2
        });
      } else {
        this.$Modal.confirm({
          title: '删除用户',
          content: `你确定要删除${this.curRow.username}么?`,
          onOk: () => {
            this.handleDeleteUser();
          },
          onCancel: () => {
            this.$Modal.remove();
          }
        });
      }
    },
    handleDeleteUser() {
      this.$axios.post(HOST + '/user/userDel',
          querystring.stringify({
            'id': this.curRow.id,
          }), {
            withCredentials: true
          }
        )
        .then((response) => {
          this.$Modal.remove();
          if (response.data.status === 'success') {
            this.$Notice.success({
              title: '更改成功',
              desc: `用户${this.curRow.username}，删除成功`,
              duration: 3
            });
            this.refreshData();
          } else {
            this.$Notice.error({
              title: '更改失败',
              desc: `用户${this.curRow.username}，删除失败`,
              duration: 3
            });
          }
          this.curRow = null;
          this.$refs.currentTable.clearCurrentRow();
        })
        .catch((err) => {
          if (err.data.status === 'invalid Token') {
            loginInvalid(this)();
          }
        });
    },
        handleChangeStatusButtonClick(status) {
      if (!this.curRow) {
        this.$Notice.warning({
          title: '未选择修改的用户',
          desc: `请点击任意一行选中想要修改的用户`,
          duration: 2
        });
      } else {
        this.$Modal.confirm({
          title: `${status === '0' ? '禁用' : '启用'}用户`,
          content: `你确定要${status === '0' ? '禁用' : '启用'}${this.curRow.username}么?`,
          onOk: () => {
            this.handleChangeUserStatus(status);
          },
          onCancel: () => {
            this.$Modal.remove();
          }
        });
      }
    },
    handleChangeUserStatus(status) {
      this.$axios.post(HOST + `/user/${status === '0' ? 'userDisable' : 'userEnable'}`,
          querystring.stringify({
            'id': this.curRow.id,
          }), {
            withCredentials: true
          }
        )
        .then((response) => {
          this.$Modal.remove();
          if (response.data.status === 'success') {
            this.$Notice.success({
              title: '更改成功',
              desc: `用户${this.curRow.username}，${status === '0' ? '禁用' : '启用'}成功`,
              duration: 3
            });
            this.refreshData();
          } else {
            this.$Notice.error({
              title: '更改失败',
              desc: `用户${this.curRow.username}，${status === '0' ? '禁用' : '启用'}失败`,
              duration: 3
            });
          }
          this.curRow = null;
          this.$refs.currentTable.clearCurrentRow();
        })
        .catch((err) => {
          if (err.data.status === 'invalid Token') {
            loginInvalid(this)();
          }
        });
    }
  },
  // TODO 注意添加用户使用的是默认的密码
  mounted() {
    this.refreshData();
    let top = this.$refs.currentTable.$el.getBoundingClientRect().top;
    let height = (window.innerHeight);
    this.tableHeight = height - top - 15;
  }
}
</script>
